<?php
namespace App\Logics;

use App\Models\ChannelModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\OrderStagesModel;
use App\Libs\Common\CsvUtil;

//逻辑处理
class AnalysisLogic extends BaseLogic {


    //订单分期日对账列表
    public function orderStagesDailyBill(array $para){
        $start_time = isset($para['start_time'])?$para['start_time']:'';
        $end_time = isset($para['end_time'])?$para['end_time']:'';

        if(empty($start_time) || empty(strtotime($start_time))){
            $start_time=date("Y-m-d",time()-86400*30);
        }
        if(empty($end_time) || empty(strtotime($end_time))){
            $end_time=date('Y-m-d',time()+86400);
        }
        if($start_time){
            $start_time=date('Y-m-d',strtotime($start_time));
        }
        if($end_time){
            $end_time=date('Y-m-d',strtotime($end_time));
        }


        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];
        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.="b.repayment_time > ? ";
            $whereCol[]=$start_time;
        }
        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="b.repayment_time <  ? ";
            $whereCol[]=$end_time;
        }

        $model=OrderModel::join('order_stages as b','b.order_id','=','orders.order_id')
            ->selectRaw("sum(b.total_pay) AS yinghuan,
                SUM(IF(b.fq_status=2,b.paid_monthly_rent,0)) AS 'paid_monthly_rent_sum',
                SUM(IF(b.fq_status=3,b.amount_override,0)) AS 'amount_override_sum',
                SUM(IF(b.fq_status=1,b.total_pay,0)) AS 'not_pay_sum',
                SUM(IF(b.fq_status=4,b.total_pay,0)) AS 'err_pay_sum',
                     left(b.repayment_time,10) AS riqi,count(*) AS count_num
                ")->where($searchWhere)->whereIn('orders.order_status',[3,4,5,8])->groupBy("repayment_time")->orderBy('b.repayment_time','desc');
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);


        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);

        $sum_ar=[
            'total_paid_monthly_rent_sum'=>0,
            'total_amount_override_sum'=>0,
            'total_not_pay_sum'=>0,
            'total_err_pay_sum'=>0,
            'total_yinghuan'=>0
        ];
        foreach ($data['data'] as $v){
            $sum_ar['total_paid_monthly_rent_sum']+=$v['paid_monthly_rent_sum'];
            $sum_ar['total_amount_override_sum']+=$v['amount_override_sum'];
            $sum_ar['total_not_pay_sum']+=$v['not_pay_sum'];
            $sum_ar['total_err_pay_sum']+=$v['err_pay_sum'];
            $sum_ar['total_yinghuan']+=$v['yinghuan'];
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url='?';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);

        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url,
            'sum_ar'=>$sum_ar
        ];
        return $arr;
    }

    /** 月账单
     * @param array $para
     * @return array
     */
    public function orderStagesMonthlyBill(array $para){
        $start_time = isset($para['start_time'])?$para['start_time']:'';
        $end_time = isset($para['end_time'])?$para['end_time']:'';
        $page = isset($para['page'])?(int)$para['page']:1;
        $per_page = isset($para['per_page'])?(int)$para['per_page']:20;

        if(empty($start_time) || empty(strtotime($start_time))){
            $start_time=date("Y-m-d",time()-86400*30);
        }
        if(empty($end_time) || empty(strtotime($end_time))){
            $end_time=date('Y-m-d',time()+86400);
        }
        if($start_time){
            $start_time=date('Y-m-d',strtotime($start_time));
        }
        if($end_time){
            $end_time=date('Y-m-d',strtotime($end_time));
        }

        $where = $searchWhere = [];
        $whereRaw=' 1 ';$whereCol=[];

        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.=" and b.repayment_time > ? ";
            $whereCol[]=$start_time;
        }
        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.=" b.repayment_time <  ? ";
            $whereCol[]=$end_time;
        }
        if($per_page){
            $where['per_page']=$per_page;
        }


        $sql="select left(b.repayment_time,7) AS riqi 
                from orders as o JOIN order_stages as b ON b.order_id=o.order_id  where ".$whereRaw." group by riqi order by b.repayment_time desc ";


        $data=[];
        $row=DB::select($sql,$whereCol);
        $total=count($row);
        $totalPage=ceil($total/$per_page);

        $url=url()->current();
        $data['first_page_url']=$url.'?page=1';
        $data['from']=($per_page-1)+1;
        $data['last_page']=$totalPage;
        $data['last_page_url']=$url.'?page='.$totalPage;
        $data['next_page_url']=$totalPage>$page?$url.'?page='.($page+1):'';
        $data['path']=$url;
        $data['per_page']=$per_page;
        $data['prev_page_url']= $page>1?$url.'?page='.($page-1):'';
        $data['to']= $per_page * $page;
        $data['total']=$total;
        $data['current_page']=$page;
        $toSize=($page-1)*$per_page;


        $sql="select sum(b.total_pay) AS yinghuan,
                SUM(IF(b.fq_status=2,b.paid_monthly_rent,0)) AS paid_monthly_rent_sum,
                SUM(IF(b.fq_status=3,b.amount_override,0)) AS amount_override_sum,
                SUM(IF(b.fq_status=1,b.total_pay,0)) AS not_pay_sum,
                SUM(IF(b.fq_status=4,b.total_pay,0)) AS err_pay_sum,
                     left(b.repayment_time,7) AS riqi,count(*) AS count_num 
                from orders as o JOIN order_stages as b ON b.order_id=o.order_id  where ".$whereRaw." group by riqi order by b.repayment_time desc  limit $toSize, $per_page";


        $list=DB::select($sql,$whereCol);
        $list=ob_to_array($list);
        $data['data']=$list;

        $sum_ar=[
            'total_paid_monthly_rent_sum'=>0,
            'total_amount_override_sum'=>0,
            'total_not_pay_sum'=>0,
            'total_err_pay_sum'=>0,
            'total_yinghuan'=>0
        ];
        foreach ($data['data'] as $v){
            $sum_ar['total_paid_monthly_rent_sum']+=$v['paid_monthly_rent_sum'];
            $sum_ar['total_amount_override_sum']+=$v['amount_override_sum'];
            $sum_ar['total_not_pay_sum']+=$v['not_pay_sum'];
            $sum_ar['total_err_pay_sum']+=$v['err_pay_sum'];
            $sum_ar['total_yinghuan']+=$v['yinghuan'];
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url='?';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);

        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url,
            'sum_ar'=>$sum_ar
        ];
        return $arr;
    }

    /** 订单数据统计
     * @return array
     */
    public function orderSummary(){
        $start_time=strtotime(date("Y-m-d"));
        $end_time=time();
        $whereRaw="unix_timestamp(order_create_time) > ? and unix_timestamp(order_create_time) <=  ? ";
        $arr=[$start_time,$end_time];

        //所有渠道的订单数量
        $channelOrderNumByDay=OrderModel::selectRaw("count(*) as num,order_comefrom")
            ->groupBy('order_comefrom')->whereRaw($whereRaw,$arr)->pluck('num','order_comefrom');
        $channelOrderNumByDay=ob_to_array($channelOrderNumByDay);

        //当天所有订单状态的数量
        $orderStatusNumByDay=OrderModel::selectRaw("count(*) as num,order_status")
            ->groupBy('order_status')->whereRaw($whereRaw,$arr)->pluck('num','order_status');
        $orderStatusNumByDay=ob_to_array($orderStatusNumByDay);

        //所有订单状态的数量
        $totalOrderStatusNum=$ar=OrderModel::selectRaw("count(*) as num,order_status")
            ->groupBy('order_status')->pluck('num','order_status');
        $totalOrderStatusNum=ob_to_array($totalOrderStatusNum);

        //查出待发货的金额
        $stayPrice = OrderModel::where('order_status','2')->sum('order_rema_amount_pay');

        // 待还款金额
        $repaymentprice =OrderModel::where('order_status',4)->sum('order_rema_amount_pay');

        // 逾期金额
        $expireprice = OrderModel::join('order_stages as s','s.order_id','=','orders.order_id')->where([['orders.order_status',8],['fq_status',3]])->selectRaw('sum((s.monthly_rent+ s.amount_override)) as num')->value('num');

        /**已完成订单金额*/
        $endprice = OrderModel::join('order_stages as s','s.order_id','=','orders.order_id')->where([['orders.order_status',5],['s.fq_status',2]])->selectRaw('sum(s.paid_monthly_rent) as num')->value('num');

        $data=[
            'channelOrderNumByDay'=>$channelOrderNumByDay,
            'orderStatusNumByDay'=>$orderStatusNumByDay,
            'totalOrderStatusNum'=>$totalOrderStatusNum,
            'stayPrice'=>$stayPrice,
            'repaymentprice'=>$repaymentprice,
            'expireprice'=>$expireprice,
            'endprice'=>$endprice,
            'nowTime'=>date('Y-m-d H:i:s')
        ];
        $order_status=config('sys.order_status');
        foreach($order_status as $k=>$v){
            if(!isset($data['orderStatusNumByDay'][$k])){
                $data['orderStatusNumByDay'][$k]=0;
            }
            if(!isset($data['totalOrderStatusNum'][$k])){
                $data['totalOrderStatusNum'][$k]=0;
            }
        }
        $channel=ChannelModel::pluck('cha_name','cha_id');
        $channel=ob_to_array($channel);
        foreach ($channel as $k=>$v){
            if(!isset($data['channelOrderNumByDay'][$k])){
                $data['channelOrderNumByDay'][$v]=0;
            }else{
                $data['channelOrderNumByDay'][$v]=$data['channelOrderNumByDay'][$k];
            }
        }

        return $data;
    }


















}